﻿/// <reference path="../../../fly/fly.js" />
/// <reference path="../../fly.ui.js" />

fly.regPlugin('dialog', function ($) {
    var ui = $.ui;
    ui.Dialog = $.Class({
        base: ui.Panel,
        constructor: function () {
            arguments.callee.$base.apply(this, arguments)
            this.content && $(this.content).hide();
            this.onBuildUI(function () {
                this.content && this.loadContent(this.content)
                this.url && this.loadUrl(this.url, this.byIframe);
            }, this);
            this.onRender(function () {
                if (this.top == "auto") {
                    var bodyH = fly.win.height()
                    var selfH = this.outer[0].clientHeight;
                    this.outer.top(Math.max((bodyH - selfH) / 2, 0))
                }

                if (this.left == "auto") {
                    var bodyW = fly.win.width()
                    var selfW = this.outer[0].clientWidth;
                    this.outer.left(Math.max((bodyW - selfW) / 2, 0))
                }
            })
        },
        baseCss: "f-dialog",
        domFrame: { el: ["titleBar", "body", "bottomBar"] },
        contentAllowScript: true,
        dragable: true,
        dragHandle: "titleBar",
        resizeable: true,
        top: "auto",
        left: 'auto',
        autoScroll: true,
        destroys: ['modalPanel'],
        showCloseButton: true,
        closeButton: null,
        escClose: true,
        buildTitleBarItems: null,
        titleBarTemplate: new ui.Template('<div class="{baseCss}-title">{title}<div class="{baseCss}-title-buttons"></div></div>'),
        createTitleBar: function () {
            var tb = this.createElement("titleBar", true);
            var items = [];
            if (this.showCloseButton) {
                var config = this.closeButton || {
                    css: this.baseCss + "-close",
                    baseCss: '',
                    tagName: 'a',
                    text: '×'
                };
                config.handler || (config.handler = this.close.bind(this))
                this.closeButton = config instanceof ui.Control ? config : new ui.SimpleButton(config);
                items.push(this.closeButton)
            }
            this.buildTitleBarItems && this.buildTitleBarItems(items);

            var buttonDiv = $(tb.dom.lastChild);
            for (var i = 0; i < items.length; i++) {
                var item = items[i]
                item.ctype || (item.ctype = "simplebutton");
                buttonDiv.append($.Component.Mgr.create(item, ui.Control));
            }

            this.closeButton && this.closeButton.el.attr('disabledrag', 1);

            return tb;
        },
        shwoBottomBar: "auto",
        buildBottomBarItems: null,
        bottomBarTemplate: new ui.Template('<div class="{baseCss}-bottom-bar"></div>'),
        createBottomBar: function () {
            if (!(this.shwoBottomBar == true || (this.shwoBottomBar == "auto" && this.bottomItems && this.bottomItems.length)))
                return null;

            this.bottomItems || (this.bottomItems = [])

            var bb = this.createElement("bottomBar", true);

            this.buildBottomBarItems && this.buildBottomBarItems(this.bottomItems);

            for (var i = 0; i < this.bottomItems.length; i++) {
                var item = this.bottomItems[i]
                item.ctype || (item.ctype = "simplebutton");
                item = this.bottomItems[i] = $.Component.Mgr.create(item, ui.Control)
                bb.append(item);
            }
            return bb;
        },

        boxControl: "body",
        posControl: "outer",
        hideIframeOnDrag: false,
        buildUI: function () {
            var me = this
            this.$base.buildUI.apply(this, arguments);
            var helperE = {
                start: function () {
                    if (me.hideIframeOnDrag)
                        me.iframeElement && me.iframeElement.hide(!$.browser.isIE67)
                },
                stoped: function () {
                    if (me.hideIframeOnDrag)
                        me.iframeElement && me.iframeElement.show()
                }
            }

            if (this.dragable) {
                var dh = $.isStr(this.dragHandle) ? this[this.dragHandle] || this.titleBar : this.dragHandle
                this.dragHelper = new $.ui.DragHelper(
                {
                    elements: this.el,
                    handle: dh,
                    dragAll: false,
                    listeners: helperE
                });
            }

            if ($.browser.isIE67) {
                function s() {
                    me.el.width(me.body[0].offsetWidth);
                }
                this.body.resize(s);
            }

            if (this.resizeable) {
                this.dragHandle = new ui.Element("<div class='" + this.baseCss + "-resize-handle'></div>")
                this.el.append(this.dragHandle);
                this.resizeHelper = new ui.DragHelper(
                {
                    isResize: true,
                    elements: this.body,
                    handle: dh,
                    handle: this.dragHandle,
                    listeners: helperE
                });
            }

            this.escClose && this.el.keyup("$event.keyCode==27 && this.close()", this);
            this.el.click(this.active, this);
            this.body.focus(this.active, this);
            this.autoScroll && this.body.css('overflow', 'auto')
        },
        active: function () {
            var ac = ui.Dialog.active
            if (ac && ac != this)
                ac.el && ac.el.removeClass(ac.baseCss + "-active");
            ui.Dialog.active = this;
            this.el.addClass(this.baseCss + "-active");
        },
        onClosing: $.Event.createEventFn('closing'),
        onClose: $.Event.createEventFn('close'),
        hideOnClose: true,
        close: function () {
            var me = this
            if (this.onClosing() == false)
                return false;

            var mp = this.modalPanel
            if (mp) {
                mp.outer.animate({ opacity: 0, callback: function () {
                    mp.destroy && mp.destroy();
                    me.modalPanel = mp = null;
                }
                }, 100);
            }
            this.onClose()

            if (this.hideOnClose) {
                this.$base.hide.apply(this, arguments);
            } else {
                this.destroy()
            }
            $.browser.isIE6 && $(window).un("resize", this.ie6Resize)

            return this
        },
        ie6Resize: function () {
            this.modalPanel.outer.height(Math.max(document.body.offsetHeight, document.documentElement.offsetHeight) + "px").width(Math.max(document.body.offsetWidth, document.documentElement.offsetWidth) + "px")
        },
        _showModal: function () {
            this.modalPanel || (this.modalPanel = ui.Panel.createModal())
            this.modalPanel.render(document.body);
            this.modalPanel.outer.animate({ opacity: { from: 0, to: .06 }, before: 'show' }, 300);
            if (this.escClose) {
                this.modalPanel.outer.focus(function () {
                    this.body.focus();
                }, this);
            }

            if ($.browser.isIE6) {
                $(window).resize(this.ie6Resize, this)
                this.ie6Resize()
            }
        },
        onShowing: $.Event.createEventFn('showing'),
        onShow: $.Event.createEventFn('show'),
        show: function (modal) {
            if (this.onShowing() == false) return false;
            if (modal) {
                this._showModal()
            }
            this.$base.show.apply(this, arguments);
            this.escClose && this.body.focus()
            this.active();
            this.onShow()

        },
        onContentChange: $.Event.createEventFn('contentChange'),
        url: null,
        byIframe: true,
        loadContent: function (content) {
            this.body.text('')
            $(content).appendTo(this.body).show();
            this.onContentChange()
        },
        iframeFormat: '<iframe frameborder="no" border="0"></iframe>',
        loadUrl: function (url, byIframe, callback) {
            var me = this;
            var loadingDiv = $("<div class=" + this.baseCss + "-loading ></div>")
            me.setHtml('');
            me.body.append(loadingDiv)
            me.loadedUrl = url;
            var loaded = false;

            if (byIframe) {
                this.body.css("overflow", "hidden");
                this.iframeElement = new ui.Template(this.iframeFormat).format(this).toElement();
                this.iframeElement.hide().appendTo(me.body).dom.dialog = this;

                this.iframeElement.on("load", function () {
                    me.window = me.iframeElement[0].contentWindow
                    if (loaded || me.loadedUrl != url)
                        return;
                    loaded = true;
                    callback && callback.call(me, me.iframeElement);
                    loadingDiv.remove()
                    me.iframeElement.css("display", "inline")
                    me.onContentChange()
                }).attr("src", url);
            }
            else {
                function c(data, xhr) {
                    if (loaded || me.loadedUrl != url) return;
                    loaded = true;
                    callback && callback.call(me, data);
                    loadingDiv.remove()
                    url.isText ? me.setText(data) : me.setHtml(data);
                    me.onContentChange()
                }

                this.iframeElement && this.iframeElement.remove();
                if ($.isStr(url))
                    $.ajax.url(url).onComplete(c).get()
                else {
                    url.complete = c
                    $.ajax(url)
                }
            }
        }
    });
    $.Component.Mgr.regType("dialog", ui.Dialog);
});